package com.example.rdemo.controller;

import com.auth0.jwt.JWT;
import com.example.rdemo.entity.User;
import com.example.rdemo.entity.Vo.LoginUser;
import com.example.rdemo.service.UserService;
import com.example.rdemo.utils.JWTUtils;
import com.example.rdemo.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    //登录验证
    @PostMapping("/login")
    public ResponseResult<String> login(@RequestBody LoginUser loginUser){
        //先判断验证码是否正确
        //1如何从Redis取出保存的验证码
        String storeCode = (String) redisTemplate.opsForValue().get("captcha_code"+loginUser.getUuid());
        System.out.println(storeCode+loginUser.toString());
        //2用户输入的验证码和storeCode比对
        if(loginUser.getCode().equals(storeCode)){
            User u = userService.getUser(loginUser);
            if (u!=null){
                Map<String,String> map = new HashMap<>();
                map.put("userid",u.getUserId()+"");
                map.put("username",u.getUserName());
                map.put("avatar",u.getAvatar());
                String token = JWTUtils.getToken(map);
                redisTemplate.delete(storeCode);
                return ResponseResult.createBySuccess(200,token,"登陆成功");
            }
            return ResponseResult.createBySuccess(500,"","账号或密码错误");
        }else {
            return ResponseResult.createBySuccess(500,"","验证码错误");
        }
    }
    //获取用户信息
    @GetMapping("/getInfo")
    public ResponseResult<User> getInfo(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        System.out.println(token+" ");
        String id = JWT.decode(token.substring(token.lastIndexOf(" ")+1)).getClaim("userid").asString();
        User user = userService.getUserById(Integer.parseInt(id));
        return ResponseResult.createBySuccess(200,user,"查询成功");
    }
}
